<template>
	<view class="page-container">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">我的</text>
		</view>

		<!-- 用户信息卡片 -->
		<view class="user-card" @click="handleUserClick">
			<image class="user-avatar" :src="userInfo.avatar || '/static/fonts/logo.png'" mode="aspectFill"></image>
			<view class="user-info">
				<text class="user-nickname">{{ userInfo.isLogin ? userInfo.nickname : '点击登录' }}</text>
				<view v-if="userInfo.isLogin" class="member-badge">
					<text>{{ userInfo.memberLevel || '普通会员' }}</text>
				</view>
			</view>
			<u-icon name="arrow-right" class="arrow-icon" color="#A1887F"></u-icon>
		</view>

		<!-- 资产信息 -->
		<view class="assets-card">
			<view class="asset-item">
				<text class="asset-value">{{ userInfo.balance || 0 }}</text>
				<text class="asset-label">余额</text>
			</view>
			<view class="asset-item">
				<text class="asset-value">{{ userInfo.points || 0 }}</text>
				<text class="asset-label">积分</text>
			</view>
			<view class="asset-item">
				<text class="asset-value">{{ userInfo.coupon || 0 }}</text>
				<text class="asset-label">优惠券</text>
			</view>
		</view>

		<!-- 订单卡片 -->
		<view class="order-card">
			<view class="card-header" @click="viewAllOrders">
				<text class="card-title">我的订单</text>
				<view class="see-all">
					<text>全部订单</text>
					<u-icon name="arrow-right" size="14" color="#A1887F"></u-icon>
				</view>
			</view>
			<view class="order-types">
				<view class="order-type-item" v-for="(item, index) in orderTypes" :key="index"
					@click="navigateToOrder(item.type)">
					<u-icon :name="item.icon" size="32" color="#5C4033"></u-icon>
					<text>{{ item.name }}</text>
				</view>
			</view>
		</view>

		<!-- 我的服务 -->
		<view class="service-card">
			<view class="card-header">
				<text class="card-title">我的服务</text>
			</view>
			<view class="service-grid">
				<view class="service-item" v-for="(item, index) in toolItems" :key="index"
					@click="navigateToTool(item.type)">
					<u-icon :name="item.icon" size="28" color="#5C4033"></u-icon>
					<text class="service-title">{{ item.name }}</text>
				</view>
			</view>
		</view>

		<!-- 添加自定义TabBar组件 -->
		<custom-tab-bar></custom-tab-bar>
	</view>
</template>

<script>
import CustomTabBar from '@/components/CustomTabBar.vue'
import uIcon from '@/node_modules/uview-ui/components/u-icon/u-icon.vue'
import { userApi } from '@/src/api/user.js'

export default {
	components: {
		CustomTabBar,
		uIcon
	},
	data() {
		return {
			userInfo: {
				isLogin: false,
				nickname: '宠物爱好者',
				avatar: '',
				memberLevel: '黄金会员',
				balance: '188.00',
				points: 1234,
				coupon: 5
			},
			orderTypes: [
				{ name: '待付款', icon: 'order', type: 'unpaid' },
				{ name: '待发货', icon: 'car', type: 'unshipped' },
				{ name: '待收货', icon: 'bag', type: 'unreceived' },
				{ name: '待评价', icon: 'chat', type: 'unrated' },
				{ name: '售后', icon: 'server-fill', type: 'service' }
			],
			toolItems: [
				{ name: '会员码', icon: 'scan', type: 'memberCode' },
				{ name: '积分商城', icon: 'integral', type: 'pointMall' },
				{ name: '我的收藏', icon: 'star', type: 'favorite' },
				{ name: '地址管理', icon: 'map', type: 'address' },
				{ name: '联系客服', icon: 'server-man', type: 'customerService' },
				{ name: '帮助中心', icon: 'question-circle', type: 'help' },
				{ name: '意见反馈', icon: 'edit-pen', type: 'feedback' },
				{ name: '账户设置', icon: 'setting', type: 'accountSetting' },
				{ name: '退出登录', icon: 'close-circle', type: 'logout' }
			]
		}
	},
	onShow() {
		// 每次显示页面时检查登录状态
		this.checkLoginStatus();
		
		// 更新TabBar选中状态
		uni.$emit('updateTabBar', 3); // 3 表示"我的"
	},
	methods: {
		handleUserClick() {
			if (this.userInfo.isLogin) {
				// 跳转到用户信息页
				uni.navigateTo({ url: '/pages/my/user-info' });
			} else {
				// 跳转到登录页
				uni.navigateTo({ url: '/pages/login/index' });
			}
		},
		checkLoginStatus() {
			const token = uni.getStorageSync('token');
			const storedUserInfo = uni.getStorageSync('userInfo');
			
			if (token && storedUserInfo) {
				this.userInfo.isLogin = true;
				this.userInfo.nickname = storedUserInfo.nickname;
				this.userInfo.avatar = storedUserInfo.avatar;
				this.userInfo.memberLevel = storedUserInfo.memberLevel;
				// 可以在这里保留对余额等动态数据的API请求
				// this.loadUserAssets(); 
			} else {
				this.userInfo.isLogin = false;
				this.userInfo.nickname = '点击登录';
				this.userInfo.avatar = '/static/fonts/logo.png';
				this.userInfo.memberLevel = '';
				this.userInfo.balance = 0;
				this.userInfo.points = 0;
				this.userInfo.coupon = 0;
			}
		},
		loadUserInfo() {
			// 此方法可以保留，用于后台静默更新用户信息
			userApi.getUserInfo()
				.then(res => {
					if (res && res.code === 200 && res.data) {
						// 更新UI
						this.userInfo.nickname = res.data.nickname;
						this.userInfo.avatar = res.data.avatar;
						this.userInfo.memberLevel = res.data.memberLevel;
						// 更新本地缓存
						uni.setStorageSync('userInfo', res.data);
					}
				})
				.catch(err => {
					console.error('静默获取用户信息失败:', err);
				});
		},
		loadUserAssets() {
			// 示例：加载需要实时更新的数据
			console.log('加载用户资产...');
		},
		viewAllOrders() {
			uni.navigateTo({
				url: '/pages/order/list'
			})
		},
		navigateToOrder(type) {
			uni.navigateTo({
				url: `/pages/order/list?type=${type}`
			})
		},
		navigateToTool(type) {
			if (type === 'logout') {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							this.logout();
						}
					}
				});
				return;
			}
			if (type === 'customerService') {
			      uni.navigateTo({
			        url: '/pages/consult/index' // 跳转到客服咨询页
			      });
			      return;
			    }
			if (type === 'address') {
				uni.navigateTo({
					url: '/pages/address/index'
				});
				return;
			}
			// 根据type跳转到不同页面
			console.log('Navigate to tool:', type)
		},
		logout() {
			// 调用后端登出接口（如果需要）
			// userApi.logout().then(...)
			
			uni.removeStorageSync('token');
			uni.removeStorageSync('userInfo'); // 同时清除用户信息
			this.checkLoginStatus(); // 重新检查状态以更新UI
			uni.showToast({
				title: '已退出登录',
				icon: 'none'
			});
		}
	}
}
</script>

<style lang="scss">
.page-container {
	background-color: $page-bg-color;
	min-height: 100vh;
	padding: 0 30rpx 120rpx;
}

// 自定义导航栏
.nav-bar {
	padding: 90rpx 0 20rpx;

	.nav-title {
		font-size: 36rpx;
		font-weight: bold;
		color: $text-primary-color;
	}
}

// 用户信息卡片
.user-card {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background-color: $card-bg-color;
	border-radius: 20rpx;
	box-shadow: $shadow;
	margin-bottom: 30rpx;

	.user-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		margin-right: 25rpx;
		background-color: #f0f0f0;
	}

	.user-info {
		flex: 1;

		.user-nickname {
			font-size: 36rpx;
			font-weight: bold;
			color: $text-primary-color;
			display: block;
			margin-bottom: 10rpx;
		}

		.member-badge {
			display: inline-block;
			padding: 4rpx 12rpx;
			background: linear-gradient(to right, #FFD700, #FFA500);
			color: #fff;
			font-size: 22rpx;
			border-radius: 6rpx;
		}
	}

	.arrow-icon {
		margin-left: 20rpx;
	}
}

// 资产卡片
.assets-card {
	display: flex;
	justify-content: space-around;
	padding: 30rpx;
	background-color: $card-bg-color;
	border-radius: 20rpx;
	box-shadow: $shadow;
	margin-bottom: 30rpx;

	.asset-item {
		text-align: center;

		.asset-value {
			font-size: 34rpx;
			font-weight: bold;
			color: $text-primary-color;
			display: block;
		}

		.asset-label {
			font-size: 26rpx;
			color: $text-secondary-color;
		}
	}
}

// 订单&服务通用卡片样式
.order-card,
.service-card {
	background-color: $card-bg-color;
	border-radius: 20rpx;
	box-shadow: $shadow;
	margin-bottom: 30rpx;
	padding: 30rpx;

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;

		.card-title {
			font-size: 32rpx;
			font-weight: bold;
			color: $text-primary-color;
		}

		.see-all {
			display: flex;
			align-items: center;
			font-size: 26rpx;
			color: $text-secondary-color;
		}
	}
}

// 订单类型
.order-types {
	display: flex;
	justify-content: space-around;

	.order-type-item {
		text-align: center;
		color: $text-primary-color;
		font-size: 26rpx;

		text {
			display: block;
			margin-top: 10rpx;
		}
	}
}

// 服务网格
.service-grid {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: -30rpx;
	
	.service-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
		
		.service-title {
			display: block;
			font-size: 26rpx;
			color: $text-primary-color;
			margin-top: 10rpx;
		}
	}
}
</style>